var util = require('../../../libs/util.js');
var moment = require('../../../libs/moment.min.js');
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    change_date:moment().format('YYYY-MM-DD'),
    imgList:[],
    formType : 'add',
    is_semitrailer:false,
    feeTypeArray: [
      ['行政费用', '业务费用', '差旅费用', '车辆费用', '其它费用'],
      ['办公费用', '租赁物业费用', '活动费用', '通讯费用', '其它费用']
    ],
    feeTypeIndex: [0, 0],
    feedate:moment().format('YYYY-MM-DD'),
    feeItem:1,
    itemData:[],
    total_fee:0,
    flow_active: 0,
    flow_steps: []
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this;
    //更新数据
    that.setData({
      server:app.server,
      user_id:app.globalData.user_id
    });
    if(e.flow_node){
      that.setData({
        flow_node:Number(e.flow_node)
      });
    }
    if(e.approve_role){
      that.setData({
        approve_role:e.approve_role
      });
    }
    if(e.CO_ID){
      that.setData({
        CR_CO_ID:e.CO_ID
      });
    }
    if(e.id){
      that.setData({
        id:e.id
      });
      this.loadData();
    }
  },
  addFeeItem:function(e){
    this.setData({
      feeItem: this.data.feeItem + 1
    })
  },
  deleteFeeItem:function(e){
    var that = this;
    var index = e.currentTarget.dataset.index;
    var itemData = that.data.itemData;
    var _itemData = [];
    for(var i=0;i<itemData.length;i++){
      if(index != i){
        _itemData.push(itemData[i])
      }
    }
    this.setData({
      itemData:_itemData,
      feeItem: this.data.feeItem - 1
    })
  },
  feeTypeChange(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var itemData = that.data.itemData;
    if(!itemData[index]){
      itemData[index] = {
        fee:'',
        feeTypeIndex:that.data.feeTypeIndex,
        feedate:that.data.feedate,
        detail:'',
        imgList:[]
      }
    }
    console.log(e.detail.value)
    itemData[index].feeTypeIndex = e.detail.value;
    this.setData({
      itemData: itemData
    })
  },
  feeTypeColumnChange(e) {
    console.log(e)
    let data = {
      feeTypeArray: this.data.feeTypeArray,
      feeTypeIndex: this.data.feeTypeIndex
    };
    data.feeTypeIndex[e.detail.column] = e.detail.value;
    switch (e.detail.column) {
      case 0:
        switch (data.feeTypeIndex[0]) {
          case 0:
            data.feeTypeArray[1] = ['办公费用', '租赁物业费用', '活动费用', '通讯费用', '其它费用'];
            break;
          case 1:
            data.feeTypeArray[1] = ['接待费用', '会务费用'];
            break;
          case 2:
            data.feeTypeArray[1] = ['交通费用', '住宿费用', '出差补贴费用'];
            break;
          case 3:
              data.feeTypeArray[1] = ['油料费用', '保险及审验费用', '停车和路桥费用', '违规违章罚款', '维修费用', '其它费用'];
              break;
          case 4:
              data.feeTypeArray[1] = ['其它费用'];
              break;
        }
        data.feeTypeIndex[1] = 0;
        break;
    }
    this.setData(data);
  },
  changeMode:function(e){
    this.setData({
      mode:e.currentTarget.dataset.mode
    })
    //this.loadData();
 },
  switchChange(e) {
    console.log(e)
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    // item_value[item] = e.detail.value;
    // this.setData(item_value);

    var that = this;
    var index = e.currentTarget.dataset.index;
    var itemData = that.data.itemData;
    if(!itemData[index]){
      itemData[index] = {
        fee:'',
        feeTypeIndex:that.data.feeTypeIndex,
        feedate:that.data.feedate,
        detail:'',
        imgList:[]
      }
    }
    itemData[index][item] = e.detail.value;
    this.setData({
      itemData: itemData
    })

    if(item == 'fee'){
      var total_fee = 0;
      for(var i=0;i<itemData.length;i++){
        total_fee += Number(itemData[i].fee||0);
      }
      this.setData({
        total_fee: total_fee
      })
    }
  },
  search: function () {
    this.loadData();
  },
  loadData: function () {
    var that = this;
    wx.showLoading({
      title: '请稍候...',
    });
    util.getData("/atapi/erp/finance/costReimbursementByID",{
      user_id:app.globalData.user_id,
      CO_ID:app.globalData.CO_ID,
      id:that.data.id
    }, function (res, error) {
      console.log(res); console.log(error)
      setTimeout(function(){
        wx.hideLoading();
      },100);
      if (res.data.success) {
        that.setData(res.data.data[0][0]);
        var itemData = [];
        if(res.data.data[1].length > 0){
          var items = res.data.data[1];
          for(var i=0;i<items.length;i++){
            itemData.push({fee:items[i].fee,feedate:items[i].feedate,detail:items[i].detail,
              fee:items[i].fee,imgList:String(items[i].files).split(","),feetype:items[i].feetype});
          }
          that.setData({
            formType:'edit',
            feeItem:items.length,
            itemData:itemData,
            flowNodeData:res.data.data[2],
            flowLogData:res.data.data[3]
          })
          var flowNodeData = res.data.data[2],flowLogData = res.data.data[3];
          var flow_steps = [],flow_active = 0;
          for(var i=0;i<flowNodeData.length;i++){
            var desc = '未审批';
            if(flowLogData.length > 0 && flowLogData[i]){
              flow_active = flowLogData.length;
              desc = (flowLogData[i].approve_result == 1?"审核通过。":"审核不通过。")+flowLogData[i].approve_remark
            }
            flow_steps.push({
              id:flowNodeData[i].NODE_ID,
              text: flowNodeData[i].NODE_NAME,
              desc: desc
            })
          }
          that.setData({
            flow_active:flow_active,
            flow_steps:flow_steps
          });
          if(that.data.flow_node){
             var approve_role = String(that.data.approve_role).split("|");
             var role_role = approve_role[0],role_user = approve_role[1];
             var is_has_approve_role = false;
             if(role_user){
               var _role_user = String(role_user).split(",");
               for(var i=0;i<_role_user.length;i++){
                  console.log(_role_user[i])
                 if(Number(_role_user[i]) == Number(app.globalData.user_id)){
                  is_has_approve_role = true;
                  console.log(is_has_approve_role)
                 }
               }
             }
             if(is_has_approve_role == false && role_role){
              var _role_role = String(role_role).split(",");
              var roleData = app.globalData.roleData;
              for(var j=0;j<_role_role.length;j++){
                 for(var i=0;i<roleData.length;i++){
                    if(roleData[i].CO_ID == that.data.CR_CO_ID && roleData[i].role == _role_role[j]){
                      is_has_approve_role = true;
                      break;
                    }
                 }
              }
             }
             if(is_has_approve_role){
                that.setData({
                  modalName:'approveModal'
                })
             }
          }
        }
      } else {
        that.setData({
          
        });
      }
    });
  },
  selectProject:function(){
    wx.navigateTo({
      url: '/pages/index/warehouseList',
    })
  },
  selectVehicle:function(){
    wx.navigateTo({
      url: '/pages/index/pathSelectVehicle',
    })
  },
  selectSemitrailer:function(){
    wx.navigateTo({
      url: '/pages/vehicle/semitrailer_select',
    })
  },
  showPictrue: function (e) {
    var image = e.currentTarget.dataset.image;
    wx.previewImage({
      urls: image
    })
  },
  previewImage: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var current = e.currentTarget.dataset.url
    var imgList = that.data.imgList;
    wx.previewImage({
      current: current,
      urls: imgList
    })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  chooseImage: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var imgList = [];
    try{
      var formData = {
        'id': that.data.vehicle_id,
        'type':'maintenance'
      };
    }catch(e){}
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        wx.showLoading({
          title: '上传中...'
        });
        wx.uploadFile({
          url: app.server +'/atapi/erp/finance/uploadImage',
          header:{
            'Authorization': app.globalData.token
          },
            filePath: res.tempFilePaths[0],
            name: 'file',
            formData: formData,
            success: function (res) {
              var data = JSON.parse(res.data); console.log(data)
              if (data.success) {
                imgList.push(data.data);
                imgList = util.arrayDeleteEmpty(imgList);
                var itemData = that.data.itemData;
                if(!itemData[index]){
                  itemData[index] = {
                    fee:'',
                    feeTypeIndex:that.data.feeTypeIndex,
                    feedate:that.data.feedate,
                    detail:'',
                    imgList:[]
                  }
                }
                for(var i=0;i<itemData.length;i++){
                  if(i == index){
                    itemData[i].imgList = imgList
                  }
                }
                that.setData({
                  itemData: itemData
                });
              }else{
                wx.showToast({
                  title: "上传失败",
                  image: '/images/wrong.png',
                  duration: 2000
                });
              }
            },
            complete: function () {
              wx.hideLoading();
            }
          })
      }
    })
  },
  DelImg: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    console.log(index)
    var type = e.currentTarget.dataset.name;
    console.log(type)
    var imgList = that.data.imgList;
    var url = imgList[index];
    wx.showLoading({
      title: '删除中...'
    });
    if(url == ''){
      if (imgList.length == 1) {
        imgList = [];
      } else {
        imgList.splice(index, 1);
      }
      that.setData({
        imgList: imgList
      })
      wx.showToast({
        title: '删除成功',
        icon: 'success',
        duration: 2000,
        success: function () {

        }
      });
      return false;
    }
    util.putData("/atapi/vehicle/vehicle/deleteFile", {
      url: url
    }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
        return false;
      }
      if (res.data.success) {
        if (imgList.length == 1) {
          imgList = [];
        } else {
          imgList = util.arrayDeleteWithIndex(imgList, index,1);
        }
        that.setData({
          imgList: imgList
        })
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            
          }
        });
      }
    });
  },
  submitFormData:function(){
    this.saveFormData(true)
  },
  //提交表单
  saveFormData: function (startFlow) {
    var that = this;

    var formData = {};

    formData.project = that.data.project||'';
    formData.projectId = that.data.projectId||'';
    formData.plate = that.data.plate||'';
    formData.vehicleId = that.data.vehicleId||'';
    formData.semitrailerId = that.data.semitrailerId||'';
    formData.total_fee = that.data.total_fee||0;
    var itemData = that.data.itemData;
    if(itemData.length == 0){
      wx.showToast({
        title: "报销金额有误",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    for(var i=0;i<itemData.length;i++){
       if(itemData[i].fee == '' || itemData[i].fee == undefined || isNaN(itemData[i].fee) == true){
        wx.showToast({
          title: "报销金额有误",
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
       }
    }
    var item = [];
    for(var i=0;i<itemData.length;i++){
      var feetype = that.data.feeTypeArray[0][itemData[i].feeTypeIndex[0]]+','+that.data.feeTypeArray[1][itemData[i].feeTypeIndex[1]];
      item.push({
      "feetype":feetype,
      "feedate":itemData[i].feedate,
      "detail":itemData[i].detail,
      "files":itemData[i].imgList.join(","),
      "fee":itemData[i].fee});
      if(i == 0){
        formData.feetype = feetype;
      }
    }
    formData.item = JSON.stringify(item);

    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    formData.CO_ID = app.globalData.CO_ID;
    formData.ADD_USER = app.globalData.user_id;

    if(startFlow){
      formData.process = 'start';
    }else{
      formData.process = 0;
    }
    console.log(formData)
    if (that.data.formType == 'add'){
      util.postData("/atapi/erp/finance/costReimbursement", formData, function (res, error) {
        console.log(res); console.log(error)
        wx.hideLoading()
        if (res.data.success) {
          wx.showToast({
            title: "提交成功",
            icon: "success",
            duration: 3000,
            success: function () {
              setTimeout(function () {
                wx.navigateBack()
              }, 3000);
            }
          });
        } else {
          wx.showToast({
            title: "提交失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
      });
    }else{
      formData.id = that.data.ID;
      util.putData("/atapi/erp/finance/costReimbursement", formData, function (res, error) {
        console.log(res); console.log(error)
        wx.hideLoading()
        if (res.data.success) {
          wx.showToast({
            title: "编辑成功",
            icon: "success",
            duration: 3000,
            success: function () {
              setTimeout(function () {
                wx.navigateBack()
              }, 3000);
            }
          });
        } else {
          wx.showToast({
            title: "编辑失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
      });
    }
    
  },
  deleteData:function(){
    var that = this;
    var _currentData = that.data._currentData;
    wx.showModal({
      title: '温馨提示',
      content: '确定要删除吗？',
      success (res) {
        if (res.confirm) {
            util.deleteData("/atapi/erp/finance/costReimbursement", {
              id: _currentData.ID,
              user_id:app.globalData.user_id,
              CO_ID:app.globalData.CO_ID,
              truename:app.globalData.truename,
              logs:that.data.plate+','+_currentData.name+','+_currentData.site+','+_currentData.fee+','+_currentData.upkeep_time+','+_currentData.user_id
            }, function (res, error) {
              console.log(res); console.log(error)
              wx.hideLoading();
              if (error) {
                wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
                return false;
              }
              if (res.data.success) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000,
                  success: function () {
                    setTimeout(function(){
                      wx.navigateBack()
                    },3000)
                  }
                });
              }
            });
          }
        }
        })
  },
  approveNoAgree:function(){
     this.approveAgree(true)
  },
  approveAgree:function(no_agree){
    var that = this;
     var approve_result = no_agree == true?0:1;
     console.log(no_agree)
     console.log(approve_result)
     var approve_remark = that.data.approve_remark;
     wx.showModal({
      title: '温馨提示',
      content: '确定审批'+(approve_result == 1?'通过':'不通过')+'吗？',
      success (res) {
        if (res.confirm) {
            util.postData("/atapi/erp/finance/approve", {
              formname:'cost_reimbursement',
              approve_result:approve_result,
              approve_remark:approve_remark||'',
              flow_node: that.data.flow_node,
              form_id:that.data.id,
              flow_id:that.data.flowNodeData[0].FLOW_ID,
              form_name:that.data.flowNodeData[0].FORM_NAME,
              user_id:app.globalData.user_id,
              CO_ID:app.globalData.CO_ID,
              user_name:app.globalData.truename
            }, function (res, error) {
              console.log(res); console.log(error)
              wx.hideLoading();
              if (error) {
                wx.showToast({ title: '提交失败', image: '/images/wrong.svg', duration: 2000 });
                return false;
              }
              if (res.data.success) {
                wx.showToast({
                  title: '提交成功',
                  icon: 'success',
                  duration: 2000,
                  success: function () {
                    setTimeout(function(){
                      that.setData({
                        modalName:null
                      })
                      that.loadData()
                    },3000)
                  }
                });
              }
            });
          }
        }
        })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'path_warehouse',
      success: function (res) {
        console.log(res)
        if (res.data) {
          that.setData({
            project: res.data.name,
            projectId: res.data.value
          });
          wx.removeStorage({
            key: 'path_warehouse',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'path_vehicle',
      success: function (res) {
        console.log(res)
        if (res.data) {
          that.setData({
            plate: res.data.plate,
            vehicleId: res.data.ID,
            semitrailerId: ''
          });
          wx.removeStorage({
            key: 'path_vehicle',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'semitrailer_select',
      success: function (res) {
        console.log(res)
        if (res.data) {
          that.setData({
            plate: res.data.plate,
            vehicleId: '',
            semitrailerId: res.data.ID
          });
          wx.removeStorage({
            key: 'semitrailer_select',
            success: function (res) {
            }
          });
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})